package com.example.cadmin.controller;


import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.cadmin.entity.MyDept;
import com.example.cadmin.entity.MyUser;
import com.example.cadmin.entityVo.MyUserVo;
import com.example.cadmin.mapper.MyDeptMapper;
import com.example.cadmin.security.dto.JwtUserDto;
import com.example.cadmin.service.MyUserService;
import com.example.cadmin.utils.ResponseModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zzsoft
 * @since 2023-01-07
 */
@Controller
@RequestMapping("/api/user")
@Api(tags = "系统：用户管理")
public class MyUserController {
    @Resource
    private MyUserService myUserService;
    @Resource
    private MyDeptMapper myDeptMapper;

    @GetMapping("/index")
    @ApiOperation("进入用户页面")
    public String index() {
        return "user/user-list";
    }

    /**
     * 绘制部门树结构
     */
    @GetMapping("/buildDept")
    @ApiOperation("绘制部门树结构")
    @ResponseBody
    public Map<String, Object> buildDept() {
        return myUserService.buildDept();
    }

    @ResponseBody
    @GetMapping("/list")
    @ApiOperation("获取用户列表")
    public Map<String, Object> userList(@RequestParam(value = "user_name", required = false) String user_name,
                                        @RequestParam(value = "nick_name", required = false) String nick_name,
                                        @RequestParam(value = "deptId", required = false) String deptId,
                                        @RequestParam(value = "page") int page,
                                        @RequestParam(value = "limit") int limit) {
        return myUserService.userList(user_name, nick_name,deptId, page, limit);
    }

    @GetMapping("/add")
    @ApiOperation("新增用户")
    @PreAuthorize("hasAnyAuthority('user:add')")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user/user_add");
        List<MyDept> myDeptList = myDeptMapper.selectList(new QueryWrapper<MyDept>().eq("status", 1).orderByAsc("sort"));
        modelAndView.addObject("myDeptList", myDeptList);
        return modelAndView;
    }

    @PostMapping("/save")
    @ApiOperation("保存用户")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('user:add')")
    public ResponseModel save(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("userName")) || StrUtil.isEmpty(data.getStr("password"))) {
            return ResponseModel.fail("用户名和密码参数缺少");
        }
        if (myUserService.checkUserExists(data.getStr("userName")) != null) {
            return ResponseModel.fail("用户已存在,无法创建");
        }
        return myUserService.saveUser(data);
    }

    @GetMapping("/edit")
    @ApiOperation("修改用户页面")
    @PreAuthorize("hasAnyAuthority('user:edit')")
    public ModelAndView edit(@RequestParam String userId) {
        return myUserService.editView(userId);
    }

    @PostMapping("/edit")
    @ResponseBody
    @ApiOperation("修改用户数据")
    @PreAuthorize("hasAnyAuthority('user:edit')")
    public ResponseModel edit(@RequestBody JSONObject data) {
        return myUserService.editUser(data);
    }

    @DeleteMapping("/delete/{user_id}")
    @ResponseBody
    @ApiOperation("删除数据")
    @PreAuthorize("hasAnyAuthority('user:del')")
    public ResponseModel delete(@PathVariable("user_id") String user_id) {
        return myUserService.deleteUser(user_id);
    }

    @PutMapping("/changeStatus")
    @ResponseBody
    @ApiOperation("修改用户状态")
    @PreAuthorize("hasAnyAuthority('user:edit')")
    public ResponseModel changeStatus(@RequestBody JSONObject data) {
        return myUserService.changeStatus(data);
    }

    // 修改密码
    @ApiOperation("修改密码视图")
    @GetMapping("/changePwd")
    public ModelAndView changePwd() {
        ModelAndView modelAndView = new ModelAndView();
        // 获取用户信息
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getMyUser().getUserName();
        modelAndView.addObject("userName", userName);
        Integer userId = jwtUserDto.getMyUser().getUserId();
        modelAndView.addObject("userId", userId);
        modelAndView.setViewName("user/changePwd");
        return modelAndView;
    }

    @ResponseBody
    @ApiOperation("修改密码")
    @RequestMapping(value = "/change", method = RequestMethod.POST)
    public ResponseModel changePwd(@RequestBody Map<String, String> data) {
        String userId = data.get("userId");
        String userPwd = data.get("usedPwd");
        String newPwd = data.get("newPwd");
        if (StrUtil.isEmpty(userId) || StrUtil.isEmpty(userPwd) ||
                StrUtil.isEmpty(newPwd)) {
            return ResponseModel.fail("缺少参数");
        }
        MyUser myUser = myUserService.getUser(userId);
        // 效验旧密码
        if (!new BCryptPasswordEncoder().matches(userPwd, myUser.getPassword())) {
            return ResponseModel.fail("抱歉，你输入的旧密码错误,无法执行修改操作");
        }
//      // 新密码写入到数据库
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String passHash = bCryptPasswordEncoder.encode(newPwd);
        MyUser myUser1 = new MyUser();
        myUser1.setPassword(passHash);
        myUser1.setUserId(myUser.getUserId());
        int updateStatus = myUserService.changePwd(myUser1);
        if (updateStatus > 0) {
            return ResponseModel.success("修改密码成功");
        } else {
            return ResponseModel.fail("修改密码失败");
        }
    }


}
